const db = require('../db/index');
const bcrypt = require('bcryptjs');

// 获取密保问题
exports.getSecurityQuestion = (req, res) => {
  const sql = 'SELECT security_question FROM user WHERE username = ?';
  db.query(sql, [req.body.username], (err, results) => {
    if (err) {
      return res.send({
        status: 1,
        message: err.message
      });
    }
    if (results.length !== 1) {
      return res.send({
        status: 1,
        message: '用户名不存在'
      });
    }
    res.send({
      status: 0,
      message: '获取密保问题成功',
      data: { securityQuestion: results[0].security_question }
    });
  });
};

// 重置密码
exports.resetPassword = (req, res) => {
  const sql = 'SELECT * FROM user WHERE username = ?';
  db.query(sql, [req.body.username], (err, results) => {
    if (err) {
      return res.send({
        status: 1,
        message: err.message
      });
    }
    if (results.length !== 1) {
      return res.send({
        status: 1,
        message: '用户名不存在'
      });
    }
    if (results[0].security_answer !== req.body.securityAnswer) {
      return res.send({
        status: 1,
        message: '密保答案错误'
      });
    }
    const sqlstr = 'UPDATE user SET password = ? WHERE username = ?';
    const newPwd = bcrypt.hashSync(req.body.newPassword, 10);
    db.query(sqlstr, [newPwd, req.body.username], (err, results) => {
      if (err) {
        return res.send({
          status: 1,
          message: err.message
        });
      }
      if (results.affectedRows !== 1) {
        return res.send({
          status: 1,
          message: '重置密码失败'
        });
      }
      res.send({
        status: 0,
        message: '重置密码成功'
      });
    });
  });
};